const Redis = require("ioredis");

const client = new Redis({
  port: 6379, // Redis port
  host: "8.134.65.55", // Redis host
  family: 4, // 4 (IPv4) or 6 (IPv6)
  password: "123456",
  db: 0,
});

//node request模块安装命令：npm install request

const request = require("request");
const querystring = require("querystring");
const { sendError } = require("../../constant/err.type");
const { sendSuccess } = require("../../constant/success.type");
let queryData = {
  mobile: "", // 接收短信的用户手机号码
  tpl_id: "261925", // 您申请的短信模板ID，根据实际情况修改  245380
  tpl_value: "", // 您设置的模板变量，根据实际情况修改；无变量则为空
  key: "73a79f80d32e3377d941f617bddbd751", // 应用APPKEY(应用详细页查询)  6898c9eb0ed8ff65bd83180ac32dee06
};
function generateVerificationCode() {
  let code = "";
  while (code.length < 6) {
    code += Math.floor(Math.random() * 10);
  }
  return code;
}

const queryUrl = "http://v.juhe.cn/sms/send";
class SendVerificationCodeController {
  async sendVerificationCode(ctx, nuxt) {
    const verificationCode = generateVerificationCode();
    queryData.mobile = ctx.request.body.phone_number;
    queryData.tpl_value = `#code#=${verificationCode}`;
    const sendCOde = new Promise((resolve, reject) => {
      client.get(queryData.mobile, (err, result) => {
        if (err) {
          console.error("获取键值出错:", err);
          return reject("获取键值出错:", err);
        } else if (result === null) {
          console.log("键不存在");
          request.post(
            { url: queryUrl, form: querystring.stringify(queryData) },
            function (error, response, body) {
              if (!error && response.statusCode == 200) {
                const jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
                if (jsonObj) {
                  const errorCode = jsonObj.error_code;
                  const reason = jsonObj.reason;
                  if (errorCode == 0) {
                    // 请求发送成功，可根据实际逻辑修改
                    const sid = jsonObj.result.sid;
                    console.log("发送成功：短信ID：" + sid, verificationCode);
                    client.set(
                      queryData.mobile,
                      verificationCode,
                      "EX",
                      600,
                      (setErr, SetResult) => {
                        if (setErr) {
                          console.error("设置带过期时间的键值出错:", setErr);
                        } else {
                          console.log("设置成功，结果:", SetResult);
                        }
                      }
                    );
                    return resolve(verificationCode);
                  } else {
                    // 请求失
                    console.log("请求失败：" + errorCode + " " + reason);
                    return reject("请求失败：" + errorCode + " " + reason);
                  }
                } else {
                  // 可能网络异常等问题请求失败，可根据实际逻辑修改
                  console.log("解析JSON异常");
                  return reject("解析JSON异常");
                }
              } else {
                // 可能网络异常等问题请求失败，可根据实际逻辑修改
                console.log("请求异常");
                return reject("请求异常");
              }
            }
          );
        } else {
          console.log("获取的值:", result);
          return resolve(result);
        }
      });
    });
    await sendCOde
      .then((res) => {
        sendSuccess.message = "短信验证码发送成功,有效期10分钟,请及时使用。";
        sendSuccess.result = res;
        ctx.body = sendSuccess;
      })
      .catch((err) => {
        sendError.message = err;
        ctx.body = sendError;
      });
  }
}
module.exports = new SendVerificationCodeController();
